package view.impl.menu;

import java.util.Map;
import java.util.TreeMap;

import org.newdawn.slick.Graphics;

import view.impl.menu.items.IMenuItem;


/**
 * 
 * 
 * @author Julian
 *
 */
public class MenuLayer {
	
	private Map<Integer, IMenuItem> items = new TreeMap<Integer, IMenuItem>();
	
	/**
	 * Adds a menu item to this menu layer.
	 * 
	 * @param item The menu item to add.
	 * @param id The id to bound to the menu item.
	 * @return True if id is not already bound to an item, otherwise false.
	 */
	public boolean addMenuItem(IMenuItem item, int id) {
		if(items.containsKey(id)) {
			return false;
		}
		items.put(id, item);
		return true;
	}
	
	public IMenuItem getMenuItem(int id) {
		return items.get(id);
	}
	
	public void move(int deltaX, int deltaY) {
		for(IMenuItem item : items.values()) {
			item.move(deltaX, deltaY);
		}
	}
	
	public void draw(Graphics g, int windowWidth, int windowHeight) {
		for(IMenuItem item : items.values()) {
			item.draw(false, g, windowWidth, windowHeight);
		}
		//Graphics g = View.getInstance().getGraphics();
		//g.setColor(new Color(0, 1, 0));
		//g.drawRect(getPosX(), getPosY(), getWidth(), getHeight());
	}
	
	public void draw(int selectedId, Graphics g, int windowWidth, int windowHeight) {
		for(int id: items.keySet()) {
			items.get(id).draw(id == selectedId, g, windowWidth, windowHeight);
		}
	}
	
	public int getPosX() {
		int posX = 0;
		boolean set = false;
		for(IMenuItem item : items.values()) {
			if(item.getPosX() < posX || !set) {
				posX = item.getPosX();
				set = true;
			}
		}
		return posX;
	}
	
	public int getPosY() {
		int posY = 0;
		boolean set = false;
		for(IMenuItem item : items.values()) {
			if(item.getPosY() < posY || !set) {
				posY = item.getPosY();
				set = true;
			}
		}
		return posY;
	}
	
	public void setPos(int posX, int posY) {
		int deltaX = posX - getPosX();
		int deltaY = posY - getPosY();
		move(deltaX, deltaY);
		/*
		for(IMenuItem item : items.values()) {
			int relPosX = item.getPosX() - getPosX();
			int relPosY = item.getPosY() - getPosY();
			
			item.setPos(posX + relPosX, posY + relPosY);
		}
		*/
	}
	
	public int getWidth() {
		int posX1= getPosX();
		int posX2= posX1;
		for(IMenuItem item : items.values()) {
			if(item.getPosX() + item.getWidth() > posX2) {
				posX2 = item.getPosX() + item.getWidth();
			}
		}
		return posX2 - posX1;
	}
	
	public int getHeight() {
		int posY1 = getPosY();
		int posY2 = posY1;
		for(IMenuItem item : items.values()) {
			if(item.getPosY() + item.getHeight() > posY2) {
				posY2 = item.getPosY() + item.getHeight();
			}
		}
		return posY2 - posY1;
	}
}
